﻿using System;
using System.Diagnostics;
using System.Windows.Forms;
using Microsoft.TeamFoundation.VersionControl.Client;

using Microsoft.TeamFoundation.Client;

using System.Text;

namespace Microsoft.Services.TfsPolicies
{
    [Serializable]
    /*
    public class BuildStatusPolicy : PolicyBase
    {
        string _tfsServer = @"http://TFSServer:8080";
        string _tfsProject = "TfsProject";
        string _buildType = "BuildType";

        [NonSerialized]
        protected bool _disposed = false;
        [NonSerialized]
        protected IPendingCheckin _pendingCheckin;

        //public virtual event PolicyStateChangedHandler PolicyStateChanged;

        #region IPolicyDefinition

        public override string Description
        {
            get { return Strings.PolicyDescription; }
        }

        // This string is a description of the type of our policy.  It will be displayed to the
        // user when they select our policy type in the list of policies installed on the system
        // as mentioned above.
        public override string TypeDescription
        {
            get { return Strings.PolicyTypeDescriptions; }
        }

        // This string is the type of our policy.  It will be displayed to the user in a list
        // of all installed policy types when they are creating a new policy.
        public override string Type
        {
            get { return Strings.PolicyType; }
        }

        // This is a string that is stored with the policy definition on the source
        // control server.  If a user does not have our policy plugin installed, this string
        // will be displayed.  We can use this as an opportunity to explain to the user
        // how they might go about installing our policy plugin.
        public override string InstallationInstructions
        {
            get { return Strings.PolicyInstallInstructions; }
        }

        public override bool CanEdit
        {
            //TODO maybe check the role of the user trying to change?
            get { return true; }
        }

        #endregion //IPolicyDefinition

        #region IPolicyDefinition

        public override void Initialize(IPendingCheckin pendingCheckin)
        {
            if (_pendingCheckin != null)
            {
                throw new InvalidOperationException("Policy already initialized.");
            }

            if (_disposed)
            {
                throw new ObjectDisposedException(null);
            }

            _pendingCheckin = pendingCheckin;

            pendingCheckin.PendingChanges.CheckedPendingChangesChanged += new EventHandler(pendingCheckin_CheckedPendingChangesChanged);
        }

        // This method is invoked by the policy framework when the user creates a new checkin
        // policy or edits an existing checkin policy.  We can use this as an opportunity to
        // display UI specific to this policy type allowing the user to change the parameters
        // of the policy.
        public override bool Edit(IPolicyEditArgs policyEditArgs)
        {
            if (_pendingCheckin != null)
            {
                throw new ApplicationException("The policy can't be edited after it has been initialized for evaluation.");
            }

            using (BuildStatusPolicyConfiguration buildStatusPolicyConfiguration = new BuildStatusPolicyConfiguration(_tfsServer, _tfsProject, _buildType))
            {
                DialogResult formResult = buildStatusPolicyConfiguration.ShowDialog(policyEditArgs.Parent);

                if (formResult == DialogResult.OK)
                {
                    _buildType = buildStatusPolicyConfiguration.TfsBuildType;
                    _tfsProject = buildStatusPolicyConfiguration.TfsProject;
                    _tfsServer = buildStatusPolicyConfiguration.TfsServer;

                    return true;
                }
                return false;
            }
        }

        public override PolicyFailure[] Evaluate()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(null);
            }

            TeamFoundationServer teamFoundationServer = TeamFoundationServerFactory.GetServer(_tfsServer);
            BuildStore buildStore = teamFoundationServer.GetService(typeof(BuildStore)) as BuildStore;

            BuildData[] buildData = buildStore.GetListOfBuilds(_tfsProject, _buildType);

            BuildData lastBuild = this.getLastBuild(buildData);

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("Builds Returned: {0} \n", buildData.Length.ToString());
            sb.AppendFormat("Build Status: {0} \n", lastBuild.BuildStatus);
            sb.AppendFormat("Build Status ID: {0} \n", lastBuild.BuildStatusId);
            sb.AppendFormat("Finish Time: {0} \n", lastBuild.FinishTime);
            sb.AppendFormat("Build Number: {0} \n", lastBuild.BuildNumber);

            EventLog.WriteEntry("Microsoft.Services.TfsPolicies", sb.ToString());

            if (lastBuild.BuildStatus.Equals("Failed", StringComparison.OrdinalIgnoreCase))
            {
                return new PolicyFailure[] { new PolicyFailure(string.Format(Strings.PolicyPrompt, _buildType), this) };
            }
            else
            {
                return new PolicyFailure[0];
            }
        }

        // This method is called if the user double-clicks on a policy failure in the UI.
        // We can handle this as we please, potentially prompting the user to perform
        // some activity that would eliminate the policy failure.
        public override void Activate(PolicyFailure failure)
        {
            MessageBox.Show(string.Format(Strings.PolicyPrompt, _buildType), "How to fix your policy failure");
        }

        // This method is called if the user presses F1 when a policy failure is active in the UI.
        // We can handle this as we please, displaying help in whatever format is appropriate.
        // For this example, we'll just pop up a dialog.
        public override void DisplayHelp(PolicyFailure failure)
        {
            MessageBox.Show(string.Format(Strings.PolicyDisplayHelp, _buildType), "Prompt Policy Help");
        }

        #endregion IPolicyDefinition

        private void pendingCheckin_CheckedPendingChangesChanged(Object sender, EventArgs e)
        {
            if (!_disposed)
            {
                OnPolicyStateChanged(Evaluate());
            }
        }

        private BuildData getLastBuild(BuildData[] builds)
        {
            DateTime lastBuildDateTime = builds[0].FinishTime;

            int position = 0;

            for (int i = 0; i < builds.Length; i++)
            {
                if (builds[i].FinishTime > lastBuildDateTime)
                {
                    lastBuildDateTime = builds[i].FinishTime;
                    position = i;
                }
            }

            return builds[position];
        }
    }
     */
    public class BuildStatusPolicy
    {
    }
}